<?php
/*
Plugin Name: WordPress Cloud Upload
Plugin URI: https://api.dwo.cc
Description: 用于将WordPress媒体文件上传到云端存储的插件
Version: 1.6.2
Author: 小渡API
Author URI: https://api.dwo.cc
License: Apache License 2.0
License URI: http://www.apache.org/licenses/LICENSE-2.0
Text Domain: wordpress-cloud-upload
Domain Path: /languages
*/

/**
 * @package WordPressCloudUpload
 * @author 小渡API
 * @version 1.6.2
 * @link https://api.dwo.cc
 * 
 * Copyright 2025 小渡API
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

if (!defined('ABSPATH')) exit;

// 注册设置
add_action('admin_init', 'suna_register_settings');
function suna_register_settings() {
    register_setting('suna_options_group', 'suna_aid');
    register_setting('suna_options_group', 'suna_key');
    register_setting('suna_options_group', 'suna_fid'); // 文件夹ID设置
    register_setting('suna_options_group', 'suna_button_position', 'suna_sanitize_position'); // 按钮位置设置
    register_setting('suna_options_group', 'suna_api_url', 'suna_sanitize_api_url'); // API地址设置
    register_setting('suna_options_group', 'suna_button_pos_x'); // 按钮X坐标
    register_setting('suna_options_group', 'suna_button_pos_y'); // 按钮Y坐标

    
    add_settings_section(
        'suna_api_section',
        '速纳云盘API设置',
        'suna_api_section_callback',
        'suna-settings'
    );
    
    add_settings_field(
        'suna_aid',
        'AID',
        'suna_aid_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_key',
        'API Key',
        'suna_key_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_fid',
        '默认文件夹ID',
        'suna_fid_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_api_url',
        'API基础地址',
        'suna_api_url_field_callback',
        'suna-settings',
        'suna_api_section'
    );
    
    add_settings_field(
        'suna_button_position',
        '上传按钮位置',
        'suna_button_position_callback',
        'suna-settings',
        'suna_api_section'
    );
    

}



// 验证按钮位置设置
function suna_sanitize_position($input) {
    $valid_positions = array('default', 'top_left', 'top_right', 'bottom_left', 'bottom_right', 'custom');
    return in_array($input, $valid_positions) ? $input : 'default';
}

// 验证API地址
function suna_sanitize_api_url($input) {
    if (empty($input)) {
        return 'https://api.snpan.com/opapi';
    }
    return rtrim($input, '/');
}

function suna_api_section_callback() {
    echo '<p>请输入您的速纳云盘API信息 <a href="https://snpan.com?v=34" target="_blank">获取API Key和AID</a></p>';
}

function suna_aid_field_callback() {
    $aid = get_option('suna_aid');
    echo '<input type="text" name="suna_aid" value="' . esc_attr($aid) . '" class="regular-text">';
    echo '<p class="description">请在 <a href="https://snpan.com?v=34" target="_blank">速纳云盘</a> 获取您的AID</p>';
}

function suna_key_field_callback() {
    $key = get_option('suna_key');
    echo '<input type="text" name="suna_key" value="' . esc_attr($key) . '" class="regular-text">';
    echo '<p class="description">请在 <a href="https://snpan.com?v=34" target="_blank">速纳云盘</a> 获取您的API Key</p>';
}

function suna_fid_field_callback() {
    $fid = get_option('suna_fid');
    echo '<input type="text" name="suna_fid" value="' . esc_attr($fid) . '" class="regular-text" placeholder="可选，留空则上传到根目录">';
}

function suna_api_url_field_callback() {
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    echo '<input type="text" name="suna_api_url" value="' . esc_attr($api_url) . '" class="regular-text" placeholder="默认: https://api.snpan.com/opapi">';
    echo '<p class="description">API服务的基础地址，一般无需修改</p>';
}

// 按钮位置设置
function suna_button_position_callback() {
    $position = get_option('suna_button_position', 'default');
    echo '<select name="suna_button_position" class="regular-text" id="suna-button-position-select">';
    echo '<option value="default"' . selected($position, 'default', false) . '>默认位置</option>';
    echo '<option value="top_left"' . selected($position, 'top_left', false) . '>左上角</option>';
    echo '<option value="top_right"' . selected($position, 'top_right', false) . '>右上角</option>';
    echo '<option value="bottom_left"' . selected($position, 'bottom_left', false) . '>左下角</option>';
    echo '<option value="bottom_right"' . selected($position, 'bottom_right', false) . '>右下角</option>';
    echo '<option value="custom"' . selected($position, 'custom', false) . '>自定义位置（可拖拽）</option>';
    echo '</select>';
    echo '<p class="description">选择上传按钮的显示位置</p>';
}

// 添加设置菜单
add_action('admin_menu', 'suna_add_admin_menu');
function suna_add_admin_menu() {
    add_options_page(
        '速纳云盘设置',
        '速纳云盘',
        'manage_options',
        'suna-settings',
        'suna_options_page'
    );
}

function suna_options_page() {
    ?>
    <div class="wrap">
        <h1>速纳云盘设置</h1>
        <form action="options.php" method="post">
            <?php
            settings_fields('suna_options_group');
            do_settings_sections('suna-settings');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

// 添加版权信息通知
add_action('admin_footer', 'suna_show_copyright_notice');
function suna_show_copyright_notice() {
    $copyrightInfo = "速纳云盘上传插件\n\n版本：1.6.2\n作者：YourName\n官网：https://api.dwo.cc\n注册获取AID和KEY：https://snpan.com?a=34\n\n注意：本插件完全免费使用！\n请勿用于任何商业用途的非法传播。\n\n感谢您的支持！";
    
    echo '<script>
    document.addEventListener("DOMContentLoaded", function() {
        // 检查是否已经显示过版权信息
        if (!localStorage.getItem("suna_copyright_shown")) {
            // 创建通知元素
            var noticeDiv = document.createElement("div");
            noticeDiv.innerHTML = "' . str_replace("\n", "<br>", $copyrightInfo) . '";
            noticeDiv.style.cssText = "position:fixed;top:20px;right:20px;padding:15px;background:#fff;border:1px solid #ccc;box-shadow:0 2px 10px rgba(0,0,0,0.1);z-index:10000;border-radius:5px;font-size:14px;max-width:300px;";
            
            // 添加关闭按钮
            var closeBtn = document.createElement("button");
            closeBtn.innerHTML = "×";
            closeBtn.style.cssText = "position:absolute;top:5px;right:5px;background:none;border:none;font-size:18px;font-weight:bold;cursor:pointer;";
            closeBtn.onclick = function() { document.body.removeChild(noticeDiv); };
            noticeDiv.appendChild(closeBtn);
            
            // 显示通知
            document.body.appendChild(noticeDiv);
            localStorage.setItem("suna_copyright_shown", "true");
            
            // 10秒后自动隐藏
            setTimeout(function() { 
                if (document.body.contains(noticeDiv)) {
                    document.body.removeChild(noticeDiv);
                }
            }, 10000);
        }
    });
    </script>';
}

// 确保按钮显示并隐藏默认上传按钮 - 修复主题切换问题
add_action('admin_enqueue_scripts', 'suna_enqueue_scripts', 999); // 提高优先级确保执行
function suna_enqueue_scripts() {
    $screen = get_current_screen();
    // 扩展有效屏幕ID，确保覆盖所有可能的上传场景
    $valid_screens = [
        'upload', 'media', 'post', 'page', 'edit-post', 'edit-page', 
        'media-library', 'post-new', 'page-new', 'customize', 'widgets'
    ];
    
    // 即使无法获取屏幕信息，也要加载资源（解决主题切换问题）
    if (!$screen || in_array($screen->id, $valid_screens)) {
        // 添加CSS修复按钮显示问题
        wp_add_inline_style('wp-admin', '
            #suna-upload-btn { 
                display: inline-flex !important; 
                align-items: center;
                background: #007cba !important;
                color: white !important;
                border-color: #006ba1 !important;
                position: relative !important;
                z-index: 100 !important;
                padding: 4px 12px;
                text-decoration: none;
                font-size: 13px;
                line-height: 26px;
                height: 30px;
                margin: 0;
                cursor: pointer;
                border-width: 1px;
                border-style: solid;
                border-radius: 3px;
                white-space: nowrap;
                box-sizing: border-box;
                transition: all 0.2s ease;
            }
            #suna-upload-btn:hover {
                background: #006ba1 !important;
                color: white !important;
            }
            #suna-upload-btn.dragging {
                opacity: 0.8;
                cursor: grabbing;
            }
            .suna-modal { 
                display: none; 
                position: fixed; 
                top: 0; 
                left: 0; 
                width: 100%; 
                height: 100%; 
                background: rgba(0,0,0,0.7); 
                z-index: 99999; 
                overflow-y: auto;
            }
            .suna-modal-content { 
                position: absolute; 
                top: 50%; 
                left: 50%; 
                transform: translate(-50%, -50%); 
                background: white; 
                padding: 20px; 
                border-radius: 5px; 
                width: 500px; 
                max-width: 90%; 
            }
            .suna-close { 
                float: right; 
                cursor: pointer; 
                font-size: 20px; 
                line-height: 1;
                padding: 5px;
            }
            .suna-progress { 
                display: none; 
                margin-top: 15px; 
            }
            .suna-progress-bar { 
                height: 20px; 
                background: #eee; 
                border-radius: 10px; 
                overflow: hidden; 
            }
            .suna-progress-fill { 
                height: 100%; 
                background: #4CAF50; 
                width: 0%; 
                transition: width 0.3s; 
            }
            .suna-message { 
                margin-top: 15px; 
                padding: 10px; 
                border-radius: 4px; 
            }
            .suna-error { 
                background: #ffebee; 
                color: #b71c1c; 
            }
            .suna-success { 
                background: #e8f5e9; 
                color: #2e7d32; 
            }
            /* 只隐藏默认上传按钮，保留上传栏结构 */
            #plupload-upload-ui .media-button,
            .media-frame-content .upload-button:not(.suna-upload-btn),
            .insert-media-modal .media-button-insert:not(.suna-upload-btn),
            .upload-flash-bypass,
            .mce-ico.mce-i-upload,
            .wp-media-buttons .insert-media-button {
                display: none !important;
            }
            /* 上传步骤样式 */
            .suna-upload-steps {
                margin-bottom: 20px;
            }
            .suna-steps-container {
                display: flex;
                position: relative;
                margin-bottom: 20px;
            }
            .suna-step {
                flex: 1;
                text-align: center;
                position: relative;
                z-index: 2;
            }
            .suna-step-icon {
                width: 30px;
                height: 30px;
                border-radius: 50%;
                background: #eee;
                color: white;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 5px;
            }
            .suna-step.active .suna-step-icon {
                background: #007cba;
            }
            .suna-step.completed .suna-step-icon {
                background: #4CAF50;
            }
            .suna-step-label {
                font-size: 12px;
            }
            .suna-progress-line {
                position: absolute;
                top: 15px;
                left: 0;
                right: 0;
                height: 2px;
                background: #eee;
                z-index: 1;
            }
            .suna-progress-line-fill {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                background: #4CAF50;
                transition: width 0.3s;
                width: 0%;
            }
            .suna-upload-section {
                display: none;
            }
            .suna-upload-section.active {
                display: block;
            }
            .suna-fid-input {
                width: 100%;
                padding: 8px;
                margin: 10px 0;
                border: 1px solid #ddd;
                border-radius: 4px;
                box-sizing: border-box;
            }
            /* 按钮位置样式 - 调整为不贴边 */
            .suna-btn-position-top-left {
                position: fixed !important;
                top: 20px !important;
                left: 20px !important;
                margin: 0 !important;
                z-index: 1000 !important;
            }
            .suna-btn-position-top-right {
                position: fixed !important;
                top: 20px !important;
                right: 20px !important;
                margin: 0 !important;
                z-index: 1000 !important;
            }
            .suna-btn-position-bottom-left {
                position: fixed !important;
                bottom: 20px !important;
                left: 20px !important;
                margin: 0 !important;
                z-index: 1000 !important;
            }
            .suna-btn-position-bottom-right {
                position: fixed !important;
                bottom: 80px !important; /* 避开可能的滚动条 */
                right: 20px !important;
                margin: 0 !important;
                z-index: 1000 !important;
            }
            .suna-btn-position-custom {
                position: fixed !important;
                margin: 0 !important;
                z-index: 1000 !important;
            }
            /* 确保在编辑器中按钮正确显示 */
            #wp-content-media-buttons #suna-upload-btn {
                margin-left: 10px !important;
            }
            .media-toolbar .media-button-group #suna-upload-btn {
                margin-left: 10px !important;
            }
            /* 修复媒体库列表视图和网格视图的显示问题 */
            .media-frame.mode-grid #suna-upload-btn,
            .media-frame.mode-list #suna-upload-btn {
                display: inline-flex !important;
            }
            /* 修复media-new.php页面显示问题 */
            .media-new-php #wpbody-content {
                padding-bottom: 20px !important;
            }
            .media-new-php .wrap {
                margin-bottom: 20px !important;
            }
        ');
    }
}

// 强制添加上传按钮到所有媒体相关页面 - 修复主题切换问题
add_action('admin_footer', 'suna_force_upload_button', 999); // 提高优先级
function suna_force_upload_button() {
    $screen = get_current_screen();
    // 扩展有效屏幕ID，确保覆盖所有可能的上传场景
    $valid_screens = [
        'upload', 'media', 'post', 'page', 'edit-post', 'edit-page', 
        'media-library', 'post-new', 'page-new', 'customize', 'widgets'
    ];
    
    // 即使无法获取屏幕信息，也要添加按钮（解决主题切换问题）
    if (!$screen || in_array($screen->id, $valid_screens)) {
        $fid = get_option('suna_fid', '');
        $button_position = get_option('suna_button_position', 'default');
        $btn_pos_x = get_option('suna_button_pos_x', '');
        $btn_pos_y = get_option('suna_button_pos_y', '');
        $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
        ?>
        <!-- 确保按钮在所有相关页面都显示 -->
        <button id="suna-upload-btn" class="button button-primary">
            <span class="wp-media-buttons-icon dashicons dashicons-cloud-upload"></span>
            速纳云盘上传
        </button>
        
        <div class="suna-modal" id="suna-modal">
            <div class="suna-modal-content">
                <span class="suna-close">&times;</span>
                <h3>上传到速纳云盘</h3>
                
                <!-- 上传步骤指示器 -->
                <div class="suna-upload-steps">
                    <div class="suna-steps-container">
                        <div class="suna-progress-line">
                            <div class="suna-steps-progress" id="suna-steps-progress"></div>
                        </div>
                        <div class="suna-step active" id="step-1">
                            <div class="suna-step-icon">1</div>
                            <div class="suna-step-label">验证授权</div>
                        </div>
                        <div class="suna-step" id="step-2">
                            <div class="suna-step-icon">2</div>
                            <div class="suna-step-label">获取地址</div>
                        </div>
                        <div class="suna-step" id="step-3">
                            <div class="suna-step-icon">3</div>
                            <div class="suna-step-label">上传文件</div>
                        </div>
                    </div>
                </div>
                
                <!-- 步骤1: 验证授权 -->
                <div class="suna-upload-section active" id="section-1">
                    <p>正在验证您的API授权信息...</p>
                    <div id="auth-status" class="suna-message"></div>
                    <button id="verify-auth-btn" class="button button-primary">验证授权</button>
                </div>
                
                <!-- 步骤2: 获取上传地址 -->
                <div class="suna-upload-section" id="section-2">
                    <label for="suna-fid">文件夹ID (可选):</label>
                    <input type="text" id="suna-fid" class="suna-fid-input" value="<?php echo esc_attr($fid); ?>" placeholder="输入文件夹ID，留空为根目录">
                    <div id="upload-url-status" class="suna-message"></div>
                    <button id="get-upload-url-btn" class="button button-primary">获取上传地址</button>
                </div>
                
                <!-- 步骤3: 上传文件 -->
                <div class="suna-upload-section" id="section-3">
                    <label for="suna-file-input">选择文件:</label>
                    <input type="file" id="suna-file-input" accept="*">
                    <div class="suna-progress">
                        <div class="suna-progress-bar">
                            <div class="suna-progress-fill"></div>
                        </div>
                        <div id="suna-progress-text" style="text-align: center; margin-top: 5px;">0%</div>
                    </div>
                    <div id="upload-status" class="suna-message"></div>
                    <button id="start-upload-btn" class="button button-primary" disabled>开始上传</button>
                </div>
            </div>
        </div>
        
        <script>
        jQuery(document).ready(function($) {
            var modal = $('#suna-modal');
            var btn = $('#suna-upload-btn');
            var span = $('.suna-close');
            var fileInput = $('#suna-file-input');
            var progress = $('.suna-progress');
            var progressFill = $('.suna-progress-fill');
            var progressText = $('#suna-progress-text');
            var stepsProgress = $('#suna-steps-progress');
            
            // 步骤元素
            var step1 = $('#step-1');
            var step2 = $('#step-2');
            var step3 = $('#step-3');
            var section1 = $('#section-1');
            var section2 = $('#section-2');
            var section3 = $('#section-3');
            
            // 按钮和状态元素
            var verifyAuthBtn = $('#verify-auth-btn');
            var getUploadUrlBtn = $('#get-upload-url-btn');
            var startUploadBtn = $('#start-upload-btn');
            var authStatus = $('#auth-status');
            var uploadUrlStatus = $('#upload-url-status');
            var uploadStatus = $('#upload-status');
            var sunaFid = $('#suna-fid');
            
            // 存储上传过程中的数据
            var authCode = '';
            var uploadUrl = '';
            var buttonPosition = '<?php echo $button_position; ?>';
            var btnPosX = '<?php echo $btn_pos_x; ?>';
            var btnPosY = '<?php echo $btn_pos_y; ?>';
            var apiBaseUrl = '<?php echo esc_js($api_url); ?>';
            var isDragging = false;
            var offset = { x: 0, y: 0 };
            
            // 处理按钮位置 - 修复主题切换问题
            function setButtonPosition() {
                // 移除所有位置类
                btn.removeClass('suna-btn-position-top-left suna-btn-position-top-right suna-btn-position-bottom-left suna-btn-position-bottom-right suna-btn-position-custom');
                
                if (buttonPosition === 'default') {
                    // 尝试将按钮添加到媒体上传区域
                    const insertionPoints = [
                        '#plupload-upload-ui .media-button-group',
                        '.media-toolbar-primary .media-button-group',
                        '#wp-content-media-buttons',
                        '.insert-media-header .media-button-group',
                        '.mce-toolbar .mce-btn-group:last',
                        '.editor-media-upload'
                    ];
                    
                    let inserted = false;
                    // 尝试所有可能的插入点
                    for (const selector of insertionPoints) {
                        if ($(selector).length) {
                            btn.appendTo(selector);
                            btn.css('margin-left', '10px');
                            inserted = true;
                            break;
                        }
                    }
                    
                    // 如果所有插入点都失败，强制显示在右上角（确保主题切换后仍可见）
                    if (!inserted) {
                        btn.addClass('suna-btn-position-top-right');
                        $('body').append(btn); // 直接添加到body
                    }
                } else if (buttonPosition === 'custom' && btnPosX && btnPosY) {
                    // 应用自定义位置
                    btn.addClass('suna-btn-position-custom');
                    btn.css({
                        left: btnPosX + 'px',
                        top: btnPosY + 'px'
                    });
                    $('body').append(btn); // 确保按钮在DOM中
                } else {
                    // 应用预设位置
                    btn.addClass('suna-btn-position-' + buttonPosition);
                    $('body').append(btn); // 确保按钮在DOM中
                }
            }
            
            // 初始化按钮位置
            setButtonPosition();
            
            // 实现按钮拖拽功能
            if (buttonPosition === 'custom') {
                makeButtonDraggable();
            }
            
            function makeButtonDraggable() {
                btn.on('mousedown', startDrag);
                
                function startDrag(e) {
                    // 只有左键点击才触发拖拽
                    if (e.button !== 0) return;
                    
                    isDragging = true;
                    btn.addClass('dragging');
                    
                    // 计算鼠标位置与按钮左上角的偏移
                    var rect = btn[0].getBoundingClientRect();
                    offset.x = e.clientX - rect.left;
                    offset.y = e.clientY - rect.top;
                    
                    // 添加事件监听，使用捕获阶段提高响应性
                    $(document).on('mousemove', drag);
                    $(document).on('mouseup', endDrag);
                    
                    // 阻止默认行为防止文本选择等
                    e.preventDefault();
                    e.stopPropagation();
                }
                
                function drag(e) {
                    if (!isDragging) return;
                    
                    // 使用requestAnimationFrame使拖拽更平滑
                    requestAnimationFrame(function() {
                        // 获取窗口尺寸限制拖拽范围
                        var windowWidth = $(window).width();
                        var windowHeight = $(window).height();
                        var btnWidth = btn.outerWidth();
                        var btnHeight = btn.outerHeight();
                        
                        // 计算新位置
                        var newX = e.clientX - offset.x;
                        var newY = e.clientY - offset.y;
                        
                        // 限制在窗口内（增加缓冲区域防止贴边）
                        var padding = 10;
                        newX = Math.max(padding, Math.min(newX, windowWidth - btnWidth - padding));
                        newY = Math.max(padding, Math.min(newY, windowHeight - btnHeight - padding));
                        
                        // 使用CSS过渡平滑移动
                        btn.css({
                            left: newX + 'px',
                            top: newY + 'px',
                            transition: 'left 0.1s ease-out, top 0.1s ease-out'
                        });
                    });
                }
                
                function endDrag() {
                    if (!isDragging) return;
                    
                    isDragging = false;
                    btn.removeClass('dragging');
                    
                    // 保存位置到数据库
                    var finalX = parseInt(btn.css('left'));
                    var finalY = parseInt(btn.css('top'));
                    
                    // 发送AJAX请求保存位置
                    $.post(ajaxurl, {
                        action: 'suna_save_button_position',
                        x: finalX,
                        y: finalY
                    }).done(function(response) {
                        if (!response.success) {
                            console.error('保存按钮位置失败:', response.data);
                        }
                    });
                    
                    // 移除事件监听
                    $(document).off('mousemove', drag);
                    $(document).off('mouseup', endDrag);
                }
            }
            
            // 显示模态框
            btn.click(function(e) {
                // 如果是拖拽状态，不显示模态框
                if (isDragging) return;
                
                e.preventDefault();
                modal.show();
                resetUploadState();
            });
            
            // 关闭模态框
            span.click(function() {
                modal.hide();
            });
            
            $(window).click(function(event) {
                if (event.target == modal[0]) {
                    modal.hide();
                }
            });
            
            // 文件选择变化时启用上传按钮
            fileInput.change(function(e) {
                startUploadBtn.prop('disabled', this.files.length === 0);
                if (this.files.length > 0) {
                    showMessage(uploadStatus, '已选择文件: ' + this.files[0].name, 'success');
                }
            });
            
            // 验证授权
            verifyAuthBtn.click(function() {
                showMessage(authStatus, '正在验证授权信息...', 'info');
                verifyAuthBtn.prop('disabled', true);
                
                $.post(ajaxurl, {
                    action: 'suna_get_authcode'
                }).done(function(authResponse) {
                    if (!authResponse.success) {
                        showMessage(authStatus, authResponse.data, 'error');
                        verifyAuthBtn.prop('disabled', false);
                        return;
                    }
                    
                    authCode = authResponse.data.authcode;
                    showMessage(authStatus, '授权验证成功', 'success');
                    
                    // 更新步骤指示器
                    step1.removeClass('active').addClass('completed');
                    step2.addClass('active');
                    stepsProgress.css('width', '33%');
                    
                    // 切换到第二步
                    setTimeout(function() {
                        section1.removeClass('active');
                        section2.addClass('active');
                    }, 500);
                    
                }).fail(function() {
                    showMessage(authStatus, '获取授权码失败，请重试', 'error');
                    verifyAuthBtn.prop('disabled', false);
                });
            });
            
            // 获取上传地址
            getUploadUrlBtn.click(function() {
                showMessage(uploadUrlStatus, '正在获取上传地址...', 'info');
                getUploadUrlBtn.prop('disabled', true);
                
                var fid = sunaFid.val().trim();
                
                $.post(ajaxurl, {
                    action: 'suna_get_upload_url',
                    authcode: authCode,
                    fid: fid
                }).done(function(urlResponse) {
                    if (!urlResponse.success) {
                        showMessage(uploadUrlStatus, urlResponse.data, 'error');
                        getUploadUrlBtn.prop('disabled', false);
                        return;
                    }
                    
                    uploadUrl = urlResponse.data.upload_url;
                    showMessage(uploadUrlStatus, '上传地址获取成功', 'success');
                    
                    // 更新步骤指示器
                    step2.removeClass('active').addClass('completed');
                    step3.addClass('active');
                    stepsProgress.css('width', '66%');
                    
                    // 切换到第三步
                    setTimeout(function() {
                        section2.removeClass('active');
                        section3.addClass('active');
                    }, 500);
                    
                }).fail(function() {
                    showMessage(uploadUrlStatus, '获取上传地址失败，请重试', 'error');
                    getUploadUrlBtn.prop('disabled', false);
                });
            });
            
            // 开始上传
            startUploadBtn.click(function() {
                var file = fileInput[0].files[0];
                if (!file) {
                    showMessage(uploadStatus, '请选择要上传的文件', 'error');
                    return;
                }
                if (!uploadUrl) {
                    showMessage(uploadStatus, '请先获取上传地址', 'error');
                    return;
                }
                
                uploadFile(file);
            });
            
            // 上传文件函数
            function uploadFile(file) {
                showMessage(uploadStatus, '正在上传文件...', 'info');
                startUploadBtn.prop('disabled', true);
                progress.show();
                progressFill.css('width', '0%');
                progressText.text('0%');
                
                var formData = new FormData();
                formData.append('file', file);
                
                // 使用XMLHttpRequest而不是jQuery.ajax以支持进度条
                var xhr = new XMLHttpRequest();
                xhr.open('POST', uploadUrl, true);
                
                // 监听进度事件
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        var percent = Math.round((e.loaded / e.total) * 100);
                        progressFill.css('width', percent + '%');
                        progressText.text(percent + '%');
                    }
                });
                
                // 上传完成处理
                xhr.addEventListener('load', function() {
                    try {
                        // 处理可能的空响应
                        var responseText = xhr.responseText || '{"code":500,"msg":"空响应"}';
                        var result = JSON.parse(responseText);
                        
                        // 处理API错误码
                        var errorMessages = {
                            255: "权限验证失败，请检查API密钥和AID是否正确",
                            400: "请求参数错误",
                            401: "未授权访问",
                            403: "禁止访问",
                            404: "上传地址不存在",
                            500: "服务器内部错误"
                        };
                        
                        if (xhr.status === 200) {
                            if (result.code == 200 && result.data) {
                                // 处理云盘返回的链接
                                var fileUrl = result.data;
                                if (typeof fileUrl === 'object' && fileUrl.url) {
                                    fileUrl = fileUrl.url;
                                }
                                
                                // 清除可能的包裹符
                                if (typeof fileUrl === 'string') {
                                    if (fileUrl.startsWith("`")) fileUrl = fileUrl.substring(1);
                                    if (fileUrl.endsWith("`")) fileUrl = fileUrl.substring(0, fileUrl.length - 1);
                                }
                                
                                // 更新步骤指示器为完成状态
                                step3.removeClass('active').addClass('completed');
                                stepsProgress.css('width', '100%');
                                
                                // 添加到媒体库并插入编辑器
                                addToMediaLibrary(fileUrl, file.name, file.type);
                            } else {
                                // 显示API返回的错误信息
                                var errorMsg = errorMessages[result.code] || result.msg || '未知错误';
                                showMessage(uploadStatus, '上传失败: ' + errorMsg + ' (错误码: ' + result.code + ')', 'error');
                                startUploadBtn.prop('disabled', false);
                            }
                        } else {
                            // 处理HTTP错误状态
                            var errorMsg = errorMessages[xhr.status] || xhr.statusText;
                            showMessage(uploadStatus, '上传失败: HTTP ' + xhr.status + ' - ' + errorMsg, 'error');
                            startUploadBtn.prop('disabled', false);
                        }
                    } catch (e) {
                        showMessage(uploadStatus, '上传响应解析错误: ' + e.message, 'error');
                        console.error('上传响应解析错误:', e, xhr.responseText);
                        startUploadBtn.prop('disabled', false);
                    }
                });
                
                // 上传错误处理
                xhr.addEventListener('error', function() {
                    showMessage(uploadStatus, '网络错误，上传请求失败', 'error');
                    startUploadBtn.prop('disabled', false);
                });
                
                // 超时处理
                xhr.timeout = 60000; // 增加超时时间到60秒
                xhr.ontimeout = function() {
                    showMessage(uploadStatus, '上传超时，请重试', 'error');
                    startUploadBtn.prop('disabled', false);
                };
                
                // 发送CORS请求时添加适当的头部
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.send(formData);
            }
            
            // 显示消息函数
            function showMessage(element, text, type) {
                element.text(text);
                element.removeClass('suna-error suna-success');
                
                if (type === 'error') {
                    element.addClass('suna-error');
                } else if (type === 'success') {
                    element.addClass('suna-success');
                }
            }
            
            // 重置上传状态
            function resetUploadState() {
                authCode = '';
                uploadUrl = '';
                fileInput.val('');
                progress.hide();
                progressFill.css('width', '0%');
                progressText.text('0%');
                startUploadBtn.prop('disabled', true);
                
                // 重置步骤
                $('.suna-step').removeClass('active completed');
                step1.addClass('active');
                stepsProgress.css('width', '0%');
                
                // 重置消息
                $('.suna-message').text('').removeClass('suna-error suna-success');
                
                // 显示第一步
                $('.suna-upload-section').removeClass('active');
                section1.addClass('active');
                
                // 重置按钮状态
                verifyAuthBtn.prop('disabled', false);
                getUploadUrlBtn.prop('disabled', false);
            }
            
            // 添加到媒体库并插入编辑器
            function addToMediaLibrary(url, filename, filetype) {
                showMessage(uploadStatus, '正在添加到媒体库...', 'info');
                
                $.post(ajaxurl, {
                    action: 'suna_add_media',
                    url: url,
                    filename: filename,
                    filetype: filetype
                }).done(function(response) {
                    if (response.success) {
                        showMessage(uploadStatus, '上传成功！文件已添加到媒体库', 'success');
                        
                        // 插入到编辑器
                        if (typeof tinyMCE !== 'undefined' && tinyMCE.activeEditor && !tinyMCE.activeEditor.isHidden()) {
                            var ext = filename.split('.').pop().toLowerCase();
                            var imageExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
                            var videoExts = ['mp4', 'webm', 'ogg', 'mov', 'avi'];
                            var audioExts = ['mp3', 'wav', 'ogg', 'flac'];
                            
                            let content = '';
                            if (imageExts.includes(ext)) {
                                content = '<img src="' + url + '" alt="' + filename + '" style="max-width:100%;" />';
                            } else if (videoExts.includes(ext)) {
                                content = '<video src="' + url + '" controls style="max-width:100%;"></video>';
                            } else if (audioExts.includes(ext)) {
                                content = '<audio src="' + url + '" controls></audio>';
                            } else {
                                content = '<a href="' + url + '">' + filename + '</a>';
                            }
                            
                            tinyMCE.activeEditor.execCommand('mceInsertContent', false, content);
                        }
                        
                        // 刷新媒体库列表
                        if (typeof wp.media !== 'undefined' && wp.media.frame) {
                            wp.media.frame.library.reload(true);
                        }
                        
                        // 3秒后关闭模态框
                        setTimeout(function() {
                            modal.hide();
                        }, 3000);
                    } else {
                        showMessage(uploadStatus, '添加到媒体库失败: ' + response.data, 'error');
                        startUploadBtn.prop('disabled', false);
                    }
                }).fail(function() {
                    showMessage(uploadStatus, '添加到媒体库请求失败', 'error');
                    startUploadBtn.prop('disabled', false);
                });
            }
        });
        </script>
        <?php
    }
}

// 完全替换WordPress的上传处理 - 修复全域上传问题
add_filter('wp_handle_upload_prefilter', 'suna_block_default_upload', 1);
function suna_block_default_upload($file) {
    // 不限制仅管理员界面，拦截所有上传
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    
    if (!empty($aid) && !empty($key)) {
        $file['error'] = '请使用"速纳云盘上传"按钮上传文件';
    }
    return $file;
}

// 拦截WordPress的AJAX上传 - 增强全域拦截
add_action('admin_init', 'suna_intercept_ajax_upload');
function suna_intercept_ajax_upload() {
    // 拦截所有可能的上传动作
    $actions = ['upload-attachment', 'add_attachment', 'edit_attachment', 'wp_handle_upload'];
    if (isset($_POST['action']) && in_array($_POST['action'], $actions)) {
        $aid = get_option('suna_aid');
        $key = get_option('suna_key');
        
        if (!empty($aid) && !empty($key)) {
            // 直接处理上传
            suna_handle_direct_upload();
            exit;
        }
    }
}

// 额外的上传拦截点 - 确保全域覆盖
add_filter('wp_handle_upload', 'suna_intercept_wp_handle_upload', 1, 2);
function suna_intercept_wp_handle_upload($upload, $context) {
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    
    if (!empty($aid) && !empty($key)) {
        // 阻止默认上传并返回错误
        $upload['error'] = '请使用"速纳云盘上传"按钮上传文件';
    }
    return $upload;
}

function suna_handle_direct_upload() {
    if (empty($_FILES['async-upload']) && empty($_FILES['file'])) {
        wp_send_json_error(['error' => '没有文件被上传']);
    }
    
    // 支持多种文件参数名，提高兼容性
    $file = isset($_FILES['async-upload']) ? $_FILES['async-upload'] : $_FILES['file'];
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    $fid = get_option('suna_fid', '');
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    
    // 计算文件MD5
    $file_md5 = md5_file($file['tmp_name']);
    
    // 获取授权码
    $authResponse = wp_remote_get($api_url . '/GetAuthCode?aid=' . urlencode($aid) . '&key=' . urlencode($key) . '&md5=' . $file_md5, array(
        'sslverify' => false,
        'timeout' => 30,
        'headers' => array(
            'Origin' => site_url(),
            'X-Requested-With' => 'XMLHttpRequest'
        )
    ));
    
    if (is_wp_error($authResponse)) {
        wp_send_json_error(['error' => '获取授权码失败: ' . $authResponse->get_error_message()]);
    }
    
    $authBody = json_decode(wp_remote_retrieve_body($authResponse), true);
    if (!$authBody || $authBody['code'] != 200 || empty($authBody['data'])) {
        $errorMsg = $authBody['msg'] ?? '未知错误';
        $errorCode = $authBody['code'] ?? '未知';
        wp_send_json_error(['error' => "授权失败: $errorMsg (错误码: $errorCode)"]);
    }
    
    // 获取上传地址，包含文件夹ID
    $uploadUrlParams = 'authcode=' . urlencode($authBody['data']);
    if (!empty($fid)) {
        $uploadUrlParams .= '&fid=' . urlencode($fid);
    }
    
    $uploadUrlResponse = wp_remote_get($api_url . '/Getuploads?' . $uploadUrlParams, array(
        'sslverify' => false,
        'timeout' => 30,
        'headers' => array(
            'Origin' => site_url(),
            'X-Requested-With' => 'XMLHttpRequest'
        )
    ));
    
    if (is_wp_error($uploadUrlResponse)) {
        wp_send_json_error(['error' => '获取上传地址失败: ' . $uploadUrlResponse->get_error_message()]);
    }
    
    $uploadUrlBody = json_decode(wp_remote_retrieve_body($uploadUrlResponse), true);
    if (!$uploadUrlBody || $uploadUrlBody['code'] != 200 || empty($uploadUrlBody['data']['url']) || empty($uploadUrlBody['data']['query'])) {
        $errorMsg = $uploadUrlBody['msg'] ?? '未知错误';
        $errorCode = $uploadUrlBody['code'] ?? '未知';
        wp_send_json_error(['error' => "获取上传地址失败: $errorMsg (错误码: $errorCode)"]);
    }
    
    $uploadUrl = $uploadUrlBody['data']['url'] . '/upload?' . $uploadUrlBody['data']['query'];
    
    // 上传文件
    $tmp_file = $file['tmp_name'];
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $uploadUrl,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => array('file' => new CURLFile($tmp_file, $file['type'], $file['name'])),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER => array(
            'X-Requested-With: XMLHttpRequest',
            'Origin: ' . site_url()
        ),
        CURLOPT_TIMEOUT => 60 // 增加超时时间
    ));
    
    $response = curl_exec($curl);
    
    // 检查CURL错误
    if(curl_errno($curl)) {
        $curlError = curl_error($curl);
        curl_close($curl);
        wp_send_json_error(['error' => '文件上传失败: ' . $curlError, 'response' => $response]);
    }
    
    curl_close($curl);
    
    // 处理空响应
    if(empty($response)) {
        wp_send_json_error(['error' => '未收到服务器响应', 'response' => '空响应']);
    }
    
    $result = json_decode($response, true);
    
    // 处理JSON解析错误
    if(json_last_error() !== JSON_ERROR_NONE) {
        wp_send_json_error([
            'error' => '响应解析失败: ' . json_last_error_msg(),
            'response' => $response
        ]);
    }
    
    if ($result && $result['code'] == 200 && $result['data']) {
        $fileUrl = $result['data'];
        if (is_array($fileUrl) && isset($fileUrl['url'])) {
            $fileUrl = $fileUrl['url'];
        }
        
        // 清除可能的包裹符
        if (is_string($fileUrl)) {
            if (strpos($fileUrl, '`') === 0) $fileUrl = substr($fileUrl, 1);
            if (substr($fileUrl, -1) === '`') $fileUrl = substr($fileUrl, 0, -1);
        }
        
        // 创建媒体库条目
        $attachment = array(
            'post_mime_type' => $file['type'],
            'post_title' => sanitize_text_field(pathinfo($file['name'], PATHINFO_FILENAME)),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        
        $attach_id = wp_insert_attachment($attachment, '', 0);
        // 存储原始URL到自定义字段，而不是WordPress默认字段
        update_post_meta($attach_id, '_suna_cloud_url', $fileUrl);
        update_post_meta($attach_id, '_suna_cloud_file', true);
        
        // 返回WordPress期望的响应格式
        $response = array(
            'success' => true,
            'data' => array(
                'id' => $attach_id,
                'url' => $fileUrl,
                'title' => pathinfo($file['name'], PATHINFO_FILENAME)
            )
        );
        
        wp_send_json($response);
    } else {
        $errorMsg = $result['msg'] ?? '未知错误';
        $errorCode = $result['code'] ?? '未知';
        wp_send_json_error([
            'error' => "上传失败: $errorMsg (错误码: $errorCode)",
            'response' => $response
        ]);
    }
}

// AJAX获取授权码 - 修复重复响应问题
add_action('wp_ajax_suna_get_authcode', 'suna_ajax_get_authcode');
function suna_ajax_get_authcode() {
    $aid = get_option('suna_aid');
    $key = get_option('suna_key');
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    
    if (empty($aid) || empty($key)) {
        wp_send_json_error('请先在设置中配置AID和API Key');
    }
    
    // 调用速纳云盘API获取授权码
    $response = wp_remote_get($api_url . '/GetAuthCode?aid=' . urlencode($aid) . '&key=' . urlencode($key), array(
        'sslverify' => false,
        'timeout' => 30,
        'headers' => array(
            'Origin' => site_url(),
            'X-Requested-With' => 'XMLHttpRequest'
        )
    ));
    
    if (is_wp_error($response)) {
        wp_send_json_error('API请求失败: ' . $response->get_error_message());
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (!$data || $data['code'] != 200 || empty($data['data'])) {
        $errorMsg = $data['msg'] ?? '未知错误';
        $errorCode = $data['code'] ?? '未知';
        wp_send_json_error("获取授权码失败: $errorMsg (错误码: $errorCode)");
    }
    
    // 修复重复发送响应的问题
    wp_send_json_success(['authcode' => $data['data']]);
}

// AJAX获取上传地址
add_action('wp_ajax_suna_get_upload_url', 'suna_ajax_get_upload_url');
function suna_ajax_get_upload_url() {
    $authcode = $_POST['authcode'] ?? '';
    $fid = $_POST['fid'] ?? '';
    $api_url = get_option('suna_api_url', 'https://api.snpan.com/opapi');
    
    if (empty($authcode)) {
        wp_send_json_error('授权码为空');
    }
    
    // 构建上传地址参数，包含文件夹ID
    $params = 'authcode=' . urlencode($authcode);
    if (!empty($fid)) {
        $params .= '&fid=' . urlencode($fid);
    }
    
    // 调用速纳云盘API获取上传地址
    $response = wp_remote_get($api_url . '/Getuploads?' . $params, array(
        'sslverify' => false,
        'timeout' => 30,
        'headers' => array(
            'Origin' => site_url(),
            'X-Requested-With' => 'XMLHttpRequest'
        )
    ));
    
    if (is_wp_error($response)) {
        wp_send_json_error('API请求失败: ' . $response->get_error_message());
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (!$data || $data['code'] != 200 || empty($data['data']['url']) || empty($data['data']['query'])) {
        $errorMsg = $data['msg'] ?? '未知错误';
        $errorCode = $data['code'] ?? '未知';
        wp_send_json_error("获取上传地址失败: $errorMsg (错误码: $errorCode)");
    }
    
    $uploadUrl = $data['data']['url'] . '/upload?' . $data['data']['query'];
    wp_send_json_success(['upload_url' => $uploadUrl]);
}

// AJAX添加到媒体库
add_action('wp_ajax_suna_add_media', 'suna_ajax_add_media');
function suna_ajax_add_media() {
    $url = $_POST['url'] ?? '';
    $filename = $_POST['filename'] ?? 'suna-upload';
    $filetype = $_POST['filetype'] ?? 'application/octet-stream';
    
    if (empty($url)) {
        wp_send_json_error('文件URL为空');
    }
    
    // 创建媒体库条目
    $attachment = array(
        'post_mime_type' => $filetype,
        'post_title' => sanitize_text_field(pathinfo($filename, PATHINFO_FILENAME)),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    
    $attach_id = wp_insert_attachment($attachment, '', 0);
    // 存储原始URL到自定义字段，而不是WordPress默认字段
    update_post_meta($attach_id, '_suna_cloud_url', $url);
    update_post_meta($attach_id, '_suna_cloud_file', true);
    
    // 为附件生成缩略图（如果是图片）
    if (strpos($filetype, 'image/') === 0) {
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        // 使用我们的URL生成缩略图
        $attach_data = array(
            'width' => 0,
            'height' => 0,
            'file' => basename($url),
            'sizes' => array(),
            'image_meta' => array()
        );
        wp_update_attachment_metadata($attach_id, $attach_data);
    }
    
    wp_send_json_success();
}

// 保存按钮位置的AJAX处理
add_action('wp_ajax_suna_save_button_position', 'suna_ajax_save_button_position');
function suna_ajax_save_button_position() {
    if (isset($_POST['x']) && isset($_POST['y'])) {
        update_option('suna_button_pos_x', sanitize_text_field($_POST['x']));
        update_option('suna_button_pos_y', sanitize_text_field($_POST['y']));
        wp_send_json_success();
    }
    wp_send_json_error('保存失败');
}

// 修复URL显示问题 - 使用自定义URL替代WordPress默认URL
add_filter('wp_get_attachment_url', 'suna_custom_attachment_url', 10, 2);
function suna_custom_attachment_url($url, $attachment_id) {
    // 检查是否是云盘文件
    $cloud_url = get_post_meta($attachment_id, '_suna_cloud_url', true);
    if (!empty($cloud_url)) {
        return $cloud_url;
    }
    return $url;
}

// 修复媒体库列表中的URL
add_filter('wp_prepare_attachment_for_js', 'suna_prepare_attachment_for_js', 10, 3);
function suna_prepare_attachment_for_js($response, $attachment, $meta) {
    $cloud_url = get_post_meta($attachment->ID, '_suna_cloud_url', true);
    if (!empty($cloud_url)) {
        $response['url'] = $cloud_url;
        // 处理图片尺寸
        if (isset($response['sizes'])) {
            foreach ($response['sizes'] as $size => $size_data) {
                $response['sizes'][$size]['url'] = $cloud_url;
            }
        }
    }
    return $response;
}

// 额外添加编辑器上传按钮支持 - 修复post-new.php问题
add_action('media_buttons', 'suna_add_editor_upload_button', 11);
function suna_add_editor_upload_button() {
    echo '<button id="suna-upload-btn-editor" class="button button-primary" style="margin-left: 10px;">
            <span class="wp-media-buttons-icon dashicons dashicons-cloud-upload"></span>
            速纳云盘上传
          </button>';
          
    // 添加按钮点击事件绑定
    echo '<script>
    jQuery(document).ready(function($) {
        $("#suna-upload-btn-editor").click(function(e) {
            e.preventDefault();
            $("#suna-upload-btn").click();
        });
    });
    </script>';
}
